package com.inspur.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.inspur.servlet.dao.FilesUploadDao;
import com.inspur.servlet.entity.Files;
import com.inspur.servlet.service.FilesUploadService;

/**
 * Created by zhangteng on 2017/7/14.
 */
public class FilesUpload extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String FILE_DIRE_PATH = "/upload/";
    // 上传配置
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 6; // 40MB

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


		// TODO Auto-generated method stub
		
		request.setCharacterEncoding("UTF-8");  
        response.setContentType("text/html;charset=UTF-8");  
        PrintWriter out = response.getWriter();  
        
        String realPath = getServletContext().getRealPath("/");
		String uploadPath =realPath+File.separator+".."+FILE_DIRE_PATH+File.separator; 
		File file = new File(uploadPath);
		if(!file.isDirectory()){
			file.mkdirs();
		}
		
        DiskFileItemFactory dfif = new DiskFileItemFactory();  
        ServletFileUpload parser = new ServletFileUpload(dfif);  
          
        parser.setFileSizeMax(MEMORY_THRESHOLD);//设置单个文件上传的大小  
        parser.setSizeMax(MAX_FILE_SIZE);//多文件上传时总大小限制  
        
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = "";
        String realName = "";
        String filePath = "";
        String tempName = "";
        Long fileSize = 0L;
        String description = "";
        List<FileItem> items = null; 
     
        try {  
            items = parser.parseRequest(request); 
            //处理请求内容  
            if(items!=null){  
                for(FileItem item:items){  
                	if (item.isFormField()) {
                		 String name = item.getFieldName();
            	         String value = item.getString("UTF-8");
            	         System.out.println("name : " + name + ", value : " + value);
            	         if("filename".equals(name)){
            	        	 fileName = value;
            	         }else if("description".equals(name)){
            	        	 description = value;
            	         }
                	}else{
                		fileSize = item.getSize();
                		realName = item.getName(); 
                    	tempName = uuid +"."+ FilenameUtils.getExtension(realName); 
                    	filePath = FILE_DIRE_PATH + tempName;
                    	item.write(new File(uploadPath+tempName));
                	}
                }  
            } 
        } catch (Exception e) {
			e.printStackTrace();
		}  
	
        Files files = new Files();
        files.setUuid(uuid);
        files.setuFileName(fileName);
        files.setRealName(realName);
        files.setUploadDire(filePath);
        files.setUploadDate(new Date());
        files.setFileSize(fileSize);
        files.setDescription(description);
        
        try {
			this.saveFiles(files);
		} catch (Exception e) {
			e.printStackTrace();
		}
        // 跳转到 list
        //request.getRequestDispatcher("/upload/list").forward(request, response);
        JSONObject  json = new JSONObject();
        json.put("success", true);
        json.put("msg", "successfully");
        out.write(json.toString());
    }
    
    /**
     * 保存文件信息
     * @param files
     * @throws Exception
     */
    private void saveFiles(Files files) throws Exception
    {
    	FilesUploadService filesUploadService = new FilesUploadService();
    	filesUploadService.save(files);
    }
}
